package com.changgou.util;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/*****
 * @Author: 黑马训练营
 * @Description: com.changgou.oauth.config
 * Feign调用之前，会执行该拦截器方法
 ****/
public class FeignInterceptor implements RequestInterceptor {

    /***
     * 调用feign之前会执行该方法
     * @param template
     */
    @Override
    public void apply(RequestTemplate template) {
        /****
         * 如果有其他的请求头，可以一起携带过去
         * 获取当前线程中所有的属性信息
         */
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        if(servletRequestAttributes!=null){
            //获取请求的所有信息
            HttpServletRequest request = servletRequestAttributes.getRequest();
            //获取所有请求头的key
            Enumeration<String> headerNames = request.getHeaderNames();

            //循环名字
            while (headerNames.hasMoreElements()){
                //请求头名字
                String name = headerNames.nextElement();
                //获取请求头的值
                String value = request.getHeader(name);

                // 并且封装到请求头中
                template.header(name,value);
            }
        }
    }
}
